#include "loginwindow.h"
#include <QLineEdit>
#include <QPushButton>
#include <QComboBox>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QMessageBox>
#include <QFont>
#include <QFile>
#include <QPalette>
#include <QCoreApplication>
#include <QStyleFactory>
#include <QApplication>
#include <QDir>
#include <QInputDialog>
#include <QTextStream>

// C后端接口
extern "C" {
#include "../backend/user.h"
}

LoginWindow::LoginWindow(QWidget *parent)
    : QWidget(parent)
{
    setWindowTitle("校园咖啡订餐系统 - 登录");
    setFixedSize(360, 300);

    QColor mainColor(0, 174, 236);
    QPalette pal = palette();
    pal.setColor(QPalette::Window, QColor(245, 247, 250));
    setPalette(pal);
    setAutoFillBackground(true);

    QFont baseFont("微软雅黑", 12, QFont::Bold);
    QFont titleFont("微软雅黑", 18, QFont::Bold);

    QLabel* lblTitle = new QLabel("校园咖啡订餐系统");
    lblTitle->setFont(titleFont);
    lblTitle->setStyleSheet("color:#00AEEC;margin-bottom:8px;");

    QLabel* lblUser = new QLabel("账号：");
    QLabel* lblPass = new QLabel("密码：");
    QLabel* lblType = new QLabel("身份：");
    lblUser->setFont(baseFont);
    lblPass->setFont(baseFont);
    lblType->setFont(baseFont);

    editUser = new QLineEdit;
    editUser->setFont(baseFont);
    editPass = new QLineEdit;
    editPass->setFont(baseFont);
    editPass->setEchoMode(QLineEdit::Password);
    comboType = new QComboBox;
    comboType->setFont(baseFont);
    comboType->addItem("管理员", USER_TYPE_ADMIN);
    comboType->addItem("普通用户", USER_TYPE_NORMAL);

    btnLogin = new QPushButton("登录");
    btnLogin->setFont(baseFont);
    btnLogin->setStyleSheet("background:#00AEEC;color:white;border-radius:6px;padding:8px 0;font-size:15px;");

    btnInitAdmin = new QPushButton("初始化管理员");
    btnInitAdmin->setFont(baseFont);
    btnInitAdmin->setStyleSheet("background:#888;color:white;border-radius:6px;padding:8px 0;font-size:15px;");

    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(lblTitle, 0, Qt::AlignHCenter);
    mainLayout->addSpacing(10);

    QHBoxLayout* userLayout = new QHBoxLayout;
    userLayout->addWidget(lblUser);
    userLayout->addWidget(editUser);

    QHBoxLayout* passLayout = new QHBoxLayout;
    passLayout->addWidget(lblPass);
    passLayout->addWidget(editPass);

    QHBoxLayout* typeLayout = new QHBoxLayout;
    typeLayout->addWidget(lblType);
    typeLayout->addWidget(comboType);

    mainLayout->addLayout(userLayout);
    mainLayout->addLayout(passLayout);
    mainLayout->addLayout(typeLayout);
    mainLayout->addSpacing(16);
    mainLayout->addWidget(btnLogin);
    mainLayout->addWidget(btnInitAdmin);

    connect(btnLogin, &QPushButton::clicked, this, &LoginWindow::onLoginClicked);
    connect(btnInitAdmin, &QPushButton::clicked, this, &LoginWindow::onInitAdmin);
    // 记忆上次登录账号
    // 确保 data 目录存在
    // Ensure the source data directory exists (using the macro from CMake)
    // SOURCE_DATA_PATH is defined by target_compile_definitions
    QString dataDirPath = QString::fromLocal8Bit(SOURCE_DATA_PATH); // Convert C macro string to QString
    QDir().mkpath(dataDirPath);
    // Construct the full path for last_login.dat
    QString lastLoginPath = dataDirPath + "/last_login.dat";
    QFile f(lastLoginPath);
    if (f.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&f);
        QString lastUser = in.readLine().trimmed();
        if (!lastUser.isEmpty()) {
            editUser->setText(lastUser);
        }
        f.close();
    }

    // 回车键直接登录
    connect(editUser, &QLineEdit::returnPressed, this, &LoginWindow::onLoginClicked);
    connect(editPass, &QLineEdit::returnPressed, this, &LoginWindow::onLoginClicked);
}

void LoginWindow::onLoginClicked()
{
    QString username = editUser->text().trimmed();
    QString password = editPass->text();
    int userType = comboType->currentData().toInt();

    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "提示", "请输入账号和密码！");
        return;
    }

    // 加载用户数据
    UserNode* head = nullptr;
    int count = load_users("users.dat", &head); // Pass only filename
    if (count == 0 || !head) {
        QMessageBox::critical(this, "错误", "用户数据文件不存在或为空！");
        return;
    }

    User found;
    int ok = check_user_login(head, username.toUtf8().constData(), password.toUtf8().constData(), &found);
    free_all_users(head);

    if (!ok) {
        QMessageBox::warning(this, "登录失败", "账号或密码错误！");
        return;
    }
    if (found.type != userType) {
        QMessageBox::warning(this, "登录失败", "身份选择与账号类型不符！");
        return;
    }

    // 登录成功后记忆账号
    // 确保 data 目录存在
    // Ensure the source data directory exists (using the macro from CMake)
    QString dataDirPath = QString::fromLocal8Bit(SOURCE_DATA_PATH); // Convert C macro string to QString
    QDir().mkpath(dataDirPath);
    // Construct the full path for last_login.dat
    QString lastLoginPath = dataDirPath + "/last_login.dat";
    QFile f(lastLoginPath);
    if (f.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream out(&f);
        out << username << "\n";
        f.close();
    }
    emit loginSuccess(username, found.id, userType); // Pass userId (found.id)
}

void LoginWindow::onInitAdmin()
{
    bool ok1, ok2;
    QString adminName = QInputDialog::getText(this, "初始化管理员", "请输入管理员账号：", QLineEdit::Normal, "admin", &ok1);
    if (!ok1 || adminName.trimmed().isEmpty()) return;
    QString adminPass = QInputDialog::getText(this, "初始化管理员", "请输入管理员密码：", QLineEdit::Password, "admin123", &ok2);
    if (!ok2 || adminPass.isEmpty()) return;

    // 1. 加载原有用户链表
    UserNode* head = nullptr;
    int count = load_users("users.dat", &head); // Pass only filename

    // 2. 检查是否已存在同名管理员
    UserNode* p = head;
    while (p) {
        if (QString(p->data.name) == adminName && p->data.type == USER_TYPE_ADMIN) {
            QMessageBox::warning(this, "提示", "该管理员账号已存在！");
            free_all_users(head);
            return;
        }
        p = p->next;
    }

    // 3. 分配新 id（取最大 id+1）
    int maxId = 0;
    p = head;
    while (p) {
        if (p->data.id > maxId) maxId = p->data.id;
        p = p->next;
    }
    int newId = maxId + 1;

    // 4. 构造新管理员用户
    User admin = {newId, "", "", "", "", USER_TYPE_ADMIN};
    strncpy(admin.name, adminName.toUtf8().constData(), sizeof(admin.name)-1);
    strncpy(admin.password, adminPass.toUtf8().constData(), sizeof(admin.password)-1);
    strncpy(admin.address, "校区A-管理室", sizeof(admin.address)-1);
    strncpy(admin.phone, "10000000000", sizeof(admin.phone)-1);

    // 5. 追加到链表
    add_user(&head, &admin);

    // 6. 保存回文件
    int n = save_users("users.dat", head); // Pass only filename
    free_all_users(head);

    if (n > 0) {
        QMessageBox::information(this, "成功", "管理员账号已写入，可用新账号登录！");
    } else {
        QMessageBox::critical(this, "失败", "写入管理员账号失败！");
    }
}
